import { defineStore } from 'pinia';
import type { menus } from '@/views/home/type';
 
const modules = import.meta.glob("../../views/**/*.vue");
const routeList:Array<menus> = []; 
export const useRouterStore = defineStore('router', {
    state: () => {
        return {
            menuTree: [] as any,
            paths: [] as Array<menus>,
            routeArr: [] as any
        }
    },

    actions: {
        createRoutes(data: menus, router: any) {
            this.arrange(data);
            this.routeArr = routeList;
            router.addRoute(this.routeArr[0]);
            // console.log(router.getRoutes())
        },

        arrange(data:any) {
            data.forEach((value:menus) => {
                this.unpack(value)
            });

            const children = routeList[0].children;
            this.paths.forEach((value: {[x: string]: any}, key: number) => {
                const routerObj: any = {
                    'path': value.path, 
                    'name': value.path_name, 
                    'component': modules[`../../views/${value.path_name}/index.vue`],
                    'meta': { title: value.menu_name, auth: true },
                };
                children.push(routerObj);
            });
        },

        unpack(item: menus) {
            if(item['children'].length){
                item['children'].forEach((value: menus) => {
                    this.unpack(value);
                })
            }else{
                if(item.path == '/'){
                    const routeObj: any = {
                        'path': '/',
                        'name': 'Home',
                        'redirect': '',
                        'component': modules[`../../views/home/index.vue`],
                        'meta': { 'title': '首页', 'keepAlive': true, 'auth': true },
                        'children': []
                    }
                    routeList.push(routeObj);
                    return;
                }

                // routeList.push(item);
                this.paths.push(item);
            }
        }
    }
})